package org.ithang.tools.sch;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.CopyOnWriteArrayList;

import org.apache.log4j.Logger;
import org.ithang.application.bcAddr.bean.Block;
import org.ithang.application.bcAddr.bean.EthAddr;
import org.ithang.application.bcAddr.service.BcAddrService;
import org.ithang.application.bcAddr.service.EthAddrService;
import org.ithang.application.operationLog.service.OperationLogService;
import org.ithang.system.keyvalue.bean.Keyvalue;
import org.ithang.system.keyvalue.service.KeyvalueService;
import org.ithang.tools.lang.DateUtils;
import org.ithang.tools.lang.JsonUtils;
import org.ithang.tools.redis.JedisUtils;
import org.ithang.tools.redis.Keys;
import org.ithang.tools.timer.BtRecordHandler;
import org.ithang.tools.timer.CollectHandler;
import org.ithang.tools.timer.GrantkHandler;
import org.ithang.tools.timer.StaticBonusJobHandler;
import org.ithang.tools.timer.TeamBonusJobHandler;
import org.ithang.tools.timer.WebSocketChecker;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

@Component
@Configuration      //1.主要用于标记配置类，兼备Component的效果。
@EnableScheduling  
public class AppSchedule {

	@Autowired
	private StaticBonusJobHandler staticBonusJobHandler;
	
	@Autowired
	private TeamBonusJobHandler teamBonusJobHandler;
	
	@Autowired
	private WebSocketChecker webSocketChecker;
	
	@Autowired
	private BtRecordHandler btRecordHandler;
	
	@Autowired
	private KeyvalueService keyvalueService;
	
	@Autowired
	private CollectHandler collectHandler;
	
	@Autowired
	private GrantkHandler grantkHandler;
	
	@Autowired
	private OperationLogService operationLogService;
	
	@Autowired
	private EthAddrService ethAddrService;
	
	@Autowired
	private BcAddrService bcAddrService;
	
	private final static Random r = new Random(System.currentTimeMillis());
	
	public final static List<EthAddr> addrs=new CopyOnWriteArrayList<>();
	
	private Logger logger=Logger.getLogger(AppSchedule.class);
	
	/**
	 * 
	 * 每天5点删除三个月前的日志数据
	 * 
	 */
	@Scheduled(cron=" 0 0 5 * * ?")
     private void del() {
		 try{
			 System.out.println("每天5点删除三个月前的日志数据");
			 Date d=DateUtils.agoMonth(2);
			 String ds=DateUtils.dateToStr(d, DateUtils.YYYY_MM_DD_HH_mm_ss);
			 operationLogService.updatesSQL("delete from sys_log where ctime<='"+ds+"'");
			 operationLogService.updatesSQL("delete from operation_log where create_time<='"+ds+"'");
		 }catch(Exception e){
			 e.printStackTrace();
		 }
     }
	
	/**
	 * 发放矿工费
	 * 每天六点
	 */
	//@Scheduled(cron = "0 */10 * * * ?")
	//@Scheduled(cron=" 0 0 6 * * ?")
    private void grantk() {
		 try{
			 System.out.println("发放矿工费");
			 Keyvalue kv=keyvalueService.get(Keys.ScheduleRun);
			 if(1==kv.intValue()){
				 logger.info("发放矿工费..."+DateUtils.getSystime());
				 grantkHandler.execute(null); 
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }
     }
	
	/**
	 * 归集
	 * 每天七点
	 */
	//@Scheduled(cron = "0 */10 * * * ?")
	//@Scheduled(cron=" 0 0 7 * * ?")
    private void collect() {
		 try{
			 System.out.println("归集...");
			 Keyvalue kv=keyvalueService.get(Keys.ScheduleRun);
			 if(1==kv.intValue()){
				 logger.info("发放矿工费..."+DateUtils.getSystime());
				 collectHandler.execute(null); 
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }
     }
	
	
	/**
	 * 静态分润
	 * 每天九点
	 */
    //@Scheduled(cron = "0 */2 * * * ?")
	@Scheduled(cron=" 0 0 7 * * ?")
    private void staticBonus() {
		 try{
			 System.out.println("静态分润");
			 Keyvalue kv=keyvalueService.get(Keys.ScheduleRun);
			 if(1==kv.intValue()){
				 logger.info("静态分润..."+DateUtils.getSystime());
				 staticBonusJobHandler.execute(null); 
			 }
		 }catch(Exception e){
			 e.printStackTrace();
		 }
     }
	 
	 /**
	  * 加速分润
	  * 每天九点
	  */
	//@Scheduled(cron = "0 */2 * * * ?")
	@Scheduled(cron=" 0 0 8 * * ?")
	private void teamBonus() {
		 try{
			 
				 System.out.println("加速分润");
				 Keyvalue kv=keyvalueService.get(Keys.ScheduleRun);
				 if(1==kv.intValue()){
				     logger.info("加速分润..."+DateUtils.getSystime());
				     teamBonusJobHandler.execute(null);
				 }
		  }catch(Exception e){
				 e.printStackTrace();
		 }
	 }
	 
	 /**
	   * 检测提币记录状态
	   * 每五分钟一次
	   */
     @Scheduled(cron = "0 */5 * * * ?")
	 private void btRecordStatusCheck() {
		 try{
			 System.out.println("检测提币记录状态");
			 Keyvalue kv=keyvalueService.get(Keys.ScheduleRun);
			 if(1==kv.intValue()){
			     logger.info("检测提币记录状态..."+DateUtils.getSystime());
			     btRecordHandler.execute(null);
			 }
		 }catch(Exception e){
			e.printStackTrace();
		 }
	 }
	 
     private static volatile boolean processList=false;//是否正在处理 交易记录
     private static volatile boolean processDetail=false;//是否正在处理交易结果
    
     
     /**
      * 获取每个交易的详细信息
      */
     @Scheduled(cron = "* 0/1 * * * ?")
     public void getTradeDetail(){
    	 if(!processDetail){
    		 
    		 try{
		    		 processDetail=true;
			    	 List<String> bs=bcAddrService.listsStr("select addr from bc_addr");
			    	 
			    	 if(null!=bs&&!bs.isEmpty()){
			    		 for(String b:bs){
			    			 String jsond=JedisUtils.get("block:"+b);
			    			 if(null!=jsond&&jsond.trim().length()>2){
			    				/* List<Block> data=JsonUtils.parseJsons(jsond, Block.class);
			    				 
			    				 if(null!=data&&!data.isEmpty()){
			    					 for(Block d:data){
			    						 System.out.println("处理地址:"+b+"交易信息:"+d.getHash());
			    						 ethAddrService.doOrder(d.getHash(),d.getTo(),d.getValue());	
			    						 try{
			    	        				 Thread.sleep(1000);
			    	        			 }catch(Exception e){}
			    					 }
			    				 }*/
			    				 
			    				 
			    				 List<Map<String,Object>> datas=JsonUtils.parseJsonToMaps(jsond);
			    				 if(null!=datas&&!datas.isEmpty()){
			    					 for(Map<String,Object> data:datas){
			    						 System.out.println("处理地址:"+b+"交易信息:"+data.get("hash"));
			    						 ethAddrService.doOrder(String.valueOf(data.get("hash")),String.valueOf(data.get("to")),String.valueOf(data.get("value")));	
			    						 try{
			    	        				 Thread.sleep(1000*(r.nextInt(3)+1));
			    	        			 }catch(Exception e){}
			    					 }
			    				 }
			    				 
			    			 }
			    		 }
			    	 }
    		 }catch(Exception e){
    			 e.printStackTrace();
    			 System.out.println("报错了:"+e.getMessage());
    		 }finally{
    			 processDetail=false;
    		 }
	    	 processDetail=false;
    	}
     }
     
     /**
      * 获取所有用户地址，并查询地址上的交易信息，如果查到则保存到redis中
      */
     @Scheduled(cron = "* 0/1 * * * ?")
     public void listTradeRecord(){
    	 if(!processList){
    		 
    		 try{
	    		 processList=true;
	    		 
		    	 List<String> bs=bcAddrService.listsStr("select addr from bc_addr");
		    	 
		    	 if(null!=bs&&!bs.isEmpty()){
		    		 for(String b:bs){
		    			 if(null!=b&&b.trim().length()>0){
		    				 List<Block> data=ethAddrService.listOrders(b);
		        			 if(null!=data&&!data.isEmpty()){
		        				 JedisUtils.set("block:"+b, JsonUtils.toJsonStr(data));
		        				 System.out.println("获取地址"+b+"的交易记录成功");
		        			 }else{
		        				 System.out.println("获取地址"+b+"的交易记录失败");
		        			 }
		        			 try{
		        				 Thread.sleep(1000*(r.nextInt(3)+1));
		        			 }catch(Exception e){}
		    			 }
		    			
		    		 }
		    	 }
    		 }catch(Exception e){
    			 e.printStackTrace();
    			 System.out.println("报错了:"+e.getMessage());
    		 }finally{
    			 processList=false;	 
    		 }
	    	 processList=false;
    	 }
     }
     
	
}
